package com.jd.xubobo.bookshow.domain;
/*
* 页码，为分页浏览使用
* */

import org.springframework.stereotype.Component;

@Component
public class Page {
    //状态量
    private int page;       //当前页码
    private int items;      //总共项数
    private int itemsPerPage;   //每页显示条数

    //每页显示的默认项数
    public static final int DEFAULT_ITEMS_PER_PAGE = 10;

    /**
     * 表示项数未知(<code>Integer.MAX_VALUE</code>)。
     */
    public static final int UNKNOWN_ITEMS = Integer.MAX_VALUE;

    //构造函数

    public Page() {
        this.page = 1;
        this.items = UNKNOWN_ITEMS;
        this.itemsPerPage = DEFAULT_ITEMS_PER_PAGE;
    }

    public Page(int items) {
        this(1, items, DEFAULT_ITEMS_PER_PAGE);
    }

    public Page(int page, int items, int itemsPerPage) {
        this.page = page > 0 ? page : 1;        //最小为1
        this.items = items > 0 ? items : UNKNOWN_ITEMS;
        this.itemsPerPage = itemsPerPage > 0 ? itemsPerPage : DEFAULT_ITEMS_PER_PAGE;
    }

    //得到该页第一项的偏移量
    public int getOffset(){
        return (page-1) * itemsPerPage;
    }

    //得到当前页的实际项数，注意可能是最后一页
    public int getLength(){
        return Math.min(page*itemsPerPage, items) - getOffset();
    }

    public int getFirstPage(){
        return 1;
    }
    public int getLastPage(){
        int lastLage = (items + itemsPerPage - 1) / itemsPerPage;
        if (lastLage == 0) lastLage = 1;
        return lastLage;
    }

    public int getPreviousPage(){
        return Math.max(1, page-1);
    }

    public int getNextPage(){
        return Math.min(page + 1, getLastPage());
    }

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        if (page<1 || page>getLastPage())   return;
        this.page = page;
    }

    public int getItems() {
        return items;
    }

    public void setItems(int items) {
        this.items = items;
    }

    public int getItemsPerPage() {
        return itemsPerPage;
    }

    public void setItemsPerPage(int itemsPerPage) {
        this.itemsPerPage = itemsPerPage;
    }
}
